package com.security.tencent;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class SM2Decryptor {
    public static void main(String[] args) throws Exception {
        // 读取C++生成的SM2密文文件
        String encryptedText = "MG0CIBlKwogQoLvkCqOT/UbxMI+XsJl+vXJk6KYmrYcqjUBaAiBMcjct8/y9rZV3rHGriDzzxsa42dSVh1dDIGSqMgL2ewQg5TZniwMgRrEGMzjVJO7VDgfMpuAgcui5ZowK0LHwV1IEBWk7YLHT";
        System.out.println("Encrypted Text: " + encryptedText);

        String prikeyStr = "MHcCAQEEIGbF7pbN82dk08jk4nSTjcGK1yWXRg9aeReLq9GQhXoRoAoGCCqBHM9V" +
                "AYItoUQDQgAE8L7UVUVj19iR8UkOs7ZbHGWxAg05o+S2rt0BnqKVh/GJFSr56xuG" +
                "FRdBofFaG5DXs7WfljFvm+mcyWS1SQ2Ymw==";

        // 解密SM2密文
        byte[] privateKeyBytes = Base64.getDecoder().decode(prikeyStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        Cipher cipher = Cipher.getInstance("SM2");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedData);
        System.out.println("Decrypted Text: " + decryptedText);
    }
}